#include <Windows.h>
#include <stdio.h>
#include <conio.h>

int main()
{
	WSADATA wsaData;
	SOCKET s = INVALID_SOCKET;
	int af,type,protocol;
	int iResult = 0;
	
	iResult = WSAStartup(MAKEWORD(2,2),&wsaData);
	if(iResult != 0)
		return 1;

	printf("WSAStartup: OK\n");

	s = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
	if(s == INVALID_SOCKET)
	{
		WSACleanup();
		return 2;
	}

	sockaddr_in sa;

	sa.sin_addr.S_un.S_addr = inet_addr("10.30.198.22");
	sa.sin_family = AF_INET;
	sa.sin_port = htons(5000);
	

	iResult = bind(s,(SOCKADDR*) &sa, sizeof(sa));
	if(iResult == INVALID_SOCKET)
	{
		closesocket(s);
		WSACleanup();
		return 3;
	}

	printf("bind: OK\n");

	iResult = listen(s,SOMAXCONN);
	if(iResult == SOCKET_ERROR)
	{
		closesocket(s);
		WSACleanup();
		return 3;
	}

	SOCKET s_clt = INVALID_SOCKET;
	sockaddr_in clt;
	int size = sizeof(sockaddr_in);

	s_clt = accept(s,(SOCKADDR *)&clt,&size);
	if(s_clt == INVALID_SOCKET)
	{
		closesocket(s);
		WSACleanup();
		return 4;
	}

	printf("accept: OK\n");

	char buf[1024];
	memset(buf,0,1024);

	iResult = recv(s_clt,buf,1024,0);
	if(iResult == SOCKET_ERROR)
	{
		closesocket(s);
		WSACleanup();
		return 5;
	}

	printf("recv: %s\n",buf);

	strcpy(buf,"HTTP/1.1 200 OK\n"
				"Pragma: no-cache\n"
				"Keep-Alive: timeout=15, max=100\n"
				"Connection: Keep-Alive\n"
				"Content-Type: text/html; charset=windows-1251\n"
				"\n"
				"<html><body>hello<img border=\"0\" src=\"images/Painter-Smurf.gif\" width=\"164\" height=\"139\"></body></html>\n"
				"\n");
	iResult = send(s_clt,buf,strlen(buf),0);
	if(iResult == SOCKET_ERROR)
	{
		closesocket(s);
		WSACleanup();
		return 6;
	}
	

	printf("send: %s\n",buf);

	s_clt = accept(s,(SOCKADDR *)&clt,&size);
	if(s_clt == INVALID_SOCKET)
	{
		closesocket(s);
		WSACleanup();
		return 4;
	}

	iResult = recv(s_clt,buf,1023,0);
	if(iResult == SOCKET_ERROR)
	{
		iResult = WSAGetLastError();
		printf("%d\n",iResult);
		getch();

		closesocket(s);
		WSACleanup();
		return 7;
	}

	printf("recv: %s\n",buf);

	closesocket(s);

	printf("closesocket: OK\n");

	WSACleanup();

	printf("WSACleanup: OK\n");

	getch();
}